<template>
  <view class="map-navigator app-container">
    <view style="position: relative; height: 100%; width: 100%">
      <map
        id="map"
        style="height: 100%; width: 100%"
        :longitude="longitude"
        :latitude="latitude"
        :markers="markers"
        :polyline="polyline"
      ></map>
      <cover-view class="actions my-card">
        <u-icon class="active-scale" :name="focusIcon" size="32" @click="handleMoveToLocation"></u-icon>
        <u-gap height="10"></u-gap>
        <u-icon class="active-scale" :name="refreshIcon" size="32" @click="handleRefreshLocation"></u-icon>
      </cover-view>
      <cover-view class="contacts">
        <cover-view v-if="isPicking" class="my-card">
          <cover-view class="flex items-center justify-between">
            <cover-view class="flex items-center">
              <u-avatar></u-avatar>
              <cover-view class="ml-20">{{ orderStore.detail.shop_company_location.name }}（寄）</cover-view>
            </cover-view>
            <cover-view class="flex items-center">
              <u-icon
                :name="moreIcon"
                color="#444444"
                bold
                size="32"
                @click="handleOpen(orderStore.detail.shop_company_location)"
              ></u-icon>
              <u-icon
                class="ml-20"
                :name="phoneIcon"
                color="#444444"
                bold
                size="32"
                @click="handleCall(orderStore.detail.shop_company_location.phone)"
              ></u-icon>
              <u-icon
                class="ml-20"
                :name="sendLineIcon"
                bold
                size="32"
                @click="handlePickPackage(orderStore.detail.id)"
              ></u-icon>
            </cover-view>
          </cover-view>
        </cover-view>
        <cover-view v-if="isDelivering" class="my-card">
          <cover-view class="flex items-center justify-between">
            <cover-view class="flex items-center">
              <u-avatar></u-avatar>
              <cover-view class="ml-20">{{ orderStore.detail.receiver_location.name }}（收）</cover-view>
            </cover-view>
            <cover-view class="flex">
              <u-icon
                :name="moreIcon"
                color="#444444"
                bold
                size="32"
                @click="handleOpen(orderStore.detail.shop_company_location)"
              ></u-icon>
              <u-icon
                class="ml-20"
                :name="phoneIcon"
                color="#444444"
                bold
                size="32"
                @click="handleCall(orderStore.detail.receiver_location.phone)"
              ></u-icon>
              <u-icon
                class="ml-20"
                :name="gatherLineIcon"
                bold
                size="32"
                @click="handleDelivery(orderStore.detail.id)"
              ></u-icon>
            </cover-view>
          </cover-view>
        </cover-view>
      </cover-view>
    </view>
    <!-- <view class="p-20">
      <u-button
        v-if="orderStore.detail.state == 'picking'"
        type="warning"
        shape="circle"
        size="small"
        @click="handlePickPackage"
      >
        收件
      </u-button>
      <u-button v-if="orderStore.detail.state == 'delivering'" type="primary" shape="circle" size="small">
        送达
      </u-button>
    </view> -->
  </view>
</template>

<script setup>
  import { onHide, onReady, onShow } from "@dcloudio/uni-app";
  import { computed, reactive, ref } from "vue";
  import riderIcon from "@/assets/images/rider.png";
  import senderIcon from "@/assets/images/send.png";
  import gatherIcon from "@/assets/images/gather.png";
  import { useOrderStore } from "../../store/order";
  import config from "../../common/config";
  import sendLineIcon from "@/assets/images/send-line.png";
  import gatherLineIcon from "@/assets/images/gather-line.png";
  import focusIcon from "@/assets/images/focus.png";
  import refreshIcon from "@/assets/images/refresh.png";
  import phoneIcon from "@/assets/images/phone.png";
  import moreIcon from "@/assets/images/more.png";

  const orderStore = useOrderStore();

  const props = defineProps({
    id: String,
    longitude: String,
    latitude: String,
  });

  let timer = null;

  let mapContenxt = null;

  // 自己当前位置标识
  const selfMarker = reactive({
    longitude: "",
    latitude: "",
    iconPath: riderIcon,
    width: 72,
    height: 60,
  });

  // 寄件人位置标识
  const senderMarker = reactive({
    longitude: "",
    latitude: "",
    iconPath: senderIcon,
    width: 64,
    height: 64,
  });

  // 收件人位置标识
  const gatherMarker = reactive({
    longitude: "",
    latitude: "",
    iconPath: gatherIcon,
    width: 64,
    height: 64,
  });

  const longitude = ref(Number(props.longitude));

  const latitude = ref(Number(props.latitude));

  const polyline = ref([]);

  const markers = computed(() => {
    return [selfMarker, senderMarker, gatherMarker];
  });

  // 是否正在取件
  const isPicking = computed(() => {
    return orderStore.detail.state == "picking";
  });

  // 是否正在派送
  const isDelivering = computed(() => {
    return orderStore.detail.state == "delivering";
  });

  // 获取订单详情
  async function getOrderDetail() {
    await orderStore.fetchOrderDetail({ id: props.id });
    // 寄件人标识
    senderMarker.longitude = Number(orderStore.detail.shop_company_location.longitude);
    senderMarker.latitude = Number(orderStore.detail.shop_company_location.latitude);
    // 收件人标识
    gatherMarker.longitude = Number(orderStore.detail.receiver_location.longitude);
    gatherMarker.latitude = Number(orderStore.detail.receiver_location.latitude);
  }

  // 拨打寄件人电话
  function handleCall(phoneNumber) {
    uni.makePhoneCall({
      phoneNumber,
    });
  }

  // 路线规划
  function getRouting(from, to, color = "#42b983") {
    return new Promise((resolve, reject) => {
      let key = "";
      // #ifdef H5
      key = config.WebTMAPKEY;
      // #endif
      // #ifdef MP-WEIXIN
      key = config.WeixinTMAPKEY;
      // #endif
      uni.request({
        url: config.ebicyclingUrl,
        method: "GET",
        data: {
          from,
          to,
          key,
        },
        success: (res) => {
          resolve(res);
          if (res.statusCode == 200 && res.data.status == 0) {
            let coors = res.data.result.routes[0].polyline;
            for (var i = 2; i < coors.length; i++) {
              coors[i] = coors[i - 2] + coors[i] / 1000000;
            }
            let coors_new = [];
            for (var j = 0; j < coors.length; j++) {
              coors_new.push({
                latitude: parseFloat(coors[j]),
                longitude: parseFloat(coors[j + 1]),
              });
              j++;
            }
            polyline.value.push({
              points: coors_new, //是一个数组形式的坐标点[{lat,log}]
              color, //线条的颜色
              width: 8, //宽度
              arrowLine: true, //是否带箭头
              borderWidth: 0, //线的边框宽度，还有很多参数，请看文档
            });
            resolve(res);
          } else {
            uni.$u.toast(res.data.message);
          }
        },
        fail: (res) => {
          reject(res);
        },
      });
    });
  }

  // 获取当前定位
  function handleGetLocation() {
    return new Promise((resolve, reject) => {
      uni.getLocation({
        success: async (res) => {
          // 放大地图打当前定位
          selfMarker.longitude = Number(res.longitude);
          selfMarker.latitude = Number(res.latitude);
          polyline.value = [];
          // 骑手到寄件或收件位置得路线规划
          await getRouting(
            `${selfMarker.latitude},${selfMarker.longitude}`,
            `${latitude.value},${longitude.value}`,
            "#42b983",
          );
          resolve(res);
        },
        fail: (err) => {
          uni.showModal({
            title: "提示",
            content: "获取定位失败，请检查是否开启权限",
            showCancel: true,
            confirmText: "去检查",
            success: (res) => {
              if (res.confirm) {
                uni.openSetting();
              }
            },
          });
          reject(err);
        },
      });
    });
  }

  // 开启轮询
  function startPolling() {
    timer = setInterval(() => {
      handleGetLocation();
    }, 30000);
  }

  // 关闭轮询
  function stopPolling() {
    clearInterval(timer);
    timer = null;
  }

  // 取件
  function handlePickPackage(id) {
    uni.showModal({
      title: "提示",
      content: "确认已取件？",
      success: async (res) => {
        if (res.confirm) {
          const result = await uni.getLocation();
          if (result) {
            const success = await orderStore.fetchActionOrder({
              id,
              longitude: result.longitude,
              latitude: result.latitude,
              action: "pick",
            });
            if (success) {
              await getOrderDetail();
              polyline.value = [];
              await getRouting(
                `${selfMarker.latitude},${selfMarker.longitude}`,
                `${orderStore.detail.receiver_location.latitude},${orderStore.detail.receiver_location.longitude}`,
                "#ff3423",
              );
            }
          }
        }
      },
    });
  }

  // 送达
  function handleDelivery(id) {
    uni.showModal({
      title: "提示",
      content: "确认已送达？",
      success: async (res) => {
        if (res.confirm) {
          const result = await uni.getLocation();
          if (result) {
            const success = await orderStore.fetchActionOrder({
              id,
              longitude: result.longitude,
              latitude: result.latitude,
              action: "completed",
            });
            if (success) {
              await getList();
            }
          }
        }
      },
    });
  }

  // 移动地图到中心点
  function handleMoveToLocation() {
    mapContenxt.moveToLocation({
      longitude: selfMarker.longitude,
      latitude: selfMarker.latitude,
    });
  }

  function handleRefreshLocation() {
    handleGetLocation();
  }

  function handleOpen(location) {
    uni.openLocation({
      longitude: Number(location.longitude),
      latitude: Number(location.latitude),
    });
  }

  onShow(async () => {
    await handleGetLocation();
    await getOrderDetail();
    startPolling();
  });

  onHide(() => {
    stopPolling();
  });

  onReady(() => {
    mapContenxt = uni.createMapContext("map");
  });
</script>

<style lang="scss" scoped>
  .contacts {
    width: 100%;
    position: absolute;
    left: 0;
    bottom: 40rpx;
    padding: 0 20rpx;
    box-sizing: border-box;

    .actions {
      position: absolute;
      right: 20rpx;
      top: -200rpx;
    }
  }

  .actions {
    position: absolute;
    right: 20rpx;
    top: 20rpx;
  }
</style>
